package com.wcar.frontsso.controller;

import com.alibaba.fastjson.JSON;
import com.wcar.common.entity.FrontUser;
import com.wcar.common.entity.User;
import com.wcar.common.util.WebUtil;
import com.wcar.common.vo.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: four-wcar-idea
 * @BelongsPackage: com.wcar.sso.controller
 * @Author: 李睢康
 * @CreateTime: 2024-05-30  15:53
 */
@RestController
@RequestMapping("/mobileLogin")
public class LoginFontController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/Login")
    public Result Login(@RequestParam String username,@RequestParam String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, password);
        try{
            subject.login(usernamePasswordToken);
            String token = UUID.randomUUID().toString().replace("-", "");
            FrontUser user = (FrontUser) subject.getPrincipal();
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set("font:login:"+token, JSON.toJSONString(user),30, TimeUnit.MINUTES);
            return new Result<>(200,"登陆成功",token);
        }catch (Exception e){
            return new Result<>(500,"账号密码错误",null);
        }
    }
    @GetMapping("/Loginout")
    public Result<Integer> loginouy(){
        String token = WebUtil.getToken();
        redisTemplate.delete("font:login:"+token);
        return new Result(200,"退出成功",null);
    }

}
